var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var api = frameElement.api, W = api.opener;
var callback = api.data.callback,oper = api.data.oper;

var Utils = {
	getDaysInOneMonth:function(year, month){
		month = parseInt(month,10);
		var d= new Date(year,month,0);
		var date = new Date(year+"/"+month+"/0");
		return d.getDate();
	},
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择计划门店',
			content : 'url:'+config.BASEPATH+'base/shop/list_dialog_bymodule',
			data : {multiselect:false,module:'want'},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				Utils.check(selected.sp_code,selected.sp_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					Utils.check(selected.sp_code,selected.sp_name);
				}
			},
			cancel:true
		});
	},
	check:function(shop_code,shop_name){
		if(shop_code == ""){
			return;
		}
		var mp_year = $("#mp_year").val();
		var mp_month = $("#mp_month").val();
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'shop/plan/month_check/'+shop_code+'/'+mp_year+'/'+mp_month,
			data:{},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					var mapData = data.data;
					$("#mp_sell_money").val("");
					if(mapData.monthPlan != null){
						Public.tips({type: 1, content : '该月份计划已经制定！'});
						return;
					}
					if(mapData.planMonth == null){
						Public.tips({type: 1, content : '该店铺未制定年计划，请先制作年计划！'});
						return;
					}
					$("#mp_shop_code").val(shop_code);
					$("#shop_name").val(shop_name);
					$("#mp_sell_money").val(mapData.planMonth.pm_sell_money_plan);
					Utils.loadPreDataDay();
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
	},
	loadPreDataDay:function(){
		var mp_shop_code = $("#mp_shop_code").val();
		var mp_year = $("#mp_year").val();
		var mp_month = $("#mp_month").val();
		if(mp_shop_code == "" || mp_year == "" || mp_month == ""){
			return;
		}
		var params = '';
		params += 'shop_code='+mp_shop_code;
		params += '&year='+mp_year;
		params += '&month='+mp_month;
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'shop/plan/loadPreDataDay?'+params,
			data:{},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					var preData = data.data;
					var ids = $("#grid").jqGrid('getDataIDs');
					for(var i=0;i < ids.length;i++){
						var rowData = $("#grid").jqGrid("getRowData", ids[i]);
						if($.trim(rowData.premoney) == ""){
							$("#grid").jqGrid('setRowData',ids[i],{premoney:0});
						}
					}
					if(preData == null || preData.length == 0){
						return;
					}
					for (var i = 0; i < preData.length; i++) {
						$("#grid").jqGrid('setRowData',preData[i].day,{premoney:preData[i].money});
					}
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
	},
	doQueryEmp : function(){
		commonDia = $.dialog({
			title : '选择经办人',
			content : 'url:'+config.BASEPATH+'base/emp/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#wt_manager").val(selected.em_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#wt_manager").val(selected.em_name);
				}
			},
			cancel:true
		});
	},
	autoAllot:function(){
		var mp_sell_money = $("#mp_sell_money").val();
		if(mp_sell_money == ""){
			return;
		}
		var ids = $("#grid").jqGrid('getDataIDs');
		var money = Math.round(mp_sell_money/ids.length);
		for(var i=0;i < ids.length -1 ;i++){
			$("#grid").jqGrid('setRowData',ids[i],{ismodify:'0',planmoney:money});
		}
		$("#grid").jqGrid('setRowData',ids[ids.length -1],{ismodify:'0',planmoney:mp_sell_money- (ids.length -1)*money});
		
		var byPre = THISPAGE.$_byPreMatch.chkVal().join() ? true : false;
		if(byPre){
			var totalPreMoney = 0;
			var totalAllotMoney = 0;
			for(var i=0;i < ids.length;i++){
				var rowData = $("#grid").jqGrid("getRowData", ids[i]);
				if(rowData.ismodify == '0' && parseFloat(rowData.premoney) > 0){
					totalPreMoney += parseFloat(rowData.premoney);
					totalAllotMoney += parseFloat(rowData.planmoney);
				}
			}
			for(var i=0;i < ids.length;i++){
				var rowData = $("#grid").jqGrid("getRowData", ids[i]);
				if(rowData.ismodify == '0' && parseFloat(rowData.premoney) > 0){
					money = Math.round(totalAllotMoney*parseFloat(rowData.premoney)/totalPreMoney);
					$("#grid").jqGrid('setRowData',ids[i],{planmoney:money});
				}
			}
		}
		THISPAGE.gridTotal();
	}
};

var handle = {
	checkParamNumberEmpty:function(value,tip){
		if(value == undefined || value == null || value == '' || isNaN(value)){
			Public.tips({type: 2, content : tip});
			return false;
		}
		return true;
	},
	checkParamEmpty:function(value,tip){
		if(value == undefined || value == null || value == ''){
			Public.tips({type: 2, content : tip});
			return false;
		}
		return true;
	},
	save:function(){
		var params = {};
		var plan = {};
		plan.mp_shop_code = $("#mp_shop_code").val();
		plan.mp_month = $("#mp_month").val();
		plan.mp_year = $("#mp_year").val();
		plan.mp_sell_money = $("#mp_sell_money").val();
		plan.mp_remark = $("#mp_remark").val();
		if(!handle.checkParamEmpty(plan.mp_shop_code, '请选择店铺！')){
			return;
		}
		if(!handle.checkParamNumberEmpty(plan.mp_sell_money, '请设置计划金额！')){
			return;
		}
		if(plan.mp_sell_money == 0){
			Public.tips({type: 2, content : '请设置计划金额！'});
			return;
		}
		var daydatas = [];
		var ids = $("#grid").jqGrid('getDataIDs');
		for(var i=0;i < ids.length;i++){
			var rowData = $("#grid").jqGrid("getRowData", ids[i]);
			var item = {};
			item.mpd_day = ids[i];
			item.mpd_sell_money_pre = rowData.premoney;
			item.mpd_sell_money_plan = rowData.planmoney;
			item.mpd_remark = rowData.remark;
			if(item.mpd_sell_money_plan == ""){
				Public.tips({type: 2, content : '请计划分配到月！'});
				return;
			}
			daydatas.push(item);
		}
		params.daydatas = Public.encodeURI(JSON.stringify(daydatas));
		params.plan = Public.encodeURI(JSON.stringify(plan));
		$("#btn-save").attr("disabled",true);
		$.ajax({
			type:"POST",
			url:config.BASEPATH+"shop/plan/month_save",
			data:params,
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : '保存成功'});
					handle.loadData(data.data);
				}else{
					Public.tips({type: 1, content : data.message});
				}
				$("#btn-save").attr("disabled",false);
			}
		});
	},
	loadData:function(data){
		var pdata = {};
		pdata.id=data.mp_id;
		if(callback && typeof callback == 'function'){
			callback(pdata,oper,window);
		}
	},
	operFmatter :function(val, opt, row){
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-pencil" title="修改">&#xe60c;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-image" title="图片">&#xe654;</i>';
		html_con += '</div>';
		return html_con;
	}
};

var THISPAGE = {
	init:function (){
		this.initGrid();
		this.initDom();
		this.initEvent();
	},
	initDom:function(){
		this.initYear();
		this.initMonth();
		this.selectRow={};
		this.$_byPreMatch = $("#byPreMatch").cssCheckbox({ callback: function($_obj){
        	if($_obj.find("input")[0].checked){//选中
        	}else{//取消
        	}
		}});
	},
	initYear:function(){
		var currentYear = new Date().getFullYear();
		var data = [
		    {Code:""+parseInt(currentYear)+"",Name:""+parseInt(currentYear)+""},
			{Code:""+parseInt(currentYear+1)+"",Name:""+parseInt(currentYear+1)+""}
		];
		$('#span_year').combo({
			data:data,
			value: 'Code',
			text: 'Name',
			width :158,
			height:80,
			listId:'',
			defaultSelected: 0,
			editable: false,
			callback:{
				onChange: function(data){
					$("#mp_year").val(data.Code);
					THISPAGE.buildGridData();
					Utils.check($("#mp_shop_code").val(), $("#shop_name").val());
				}
			}
		}).getCombo();
	},
	initMonth:function(){
		var data = [
		    {Code:"1",Name:"1月份"},
		    {Code:"2",Name:"2月份"},
		    {Code:"3",Name:"3月份"},
		    {Code:"4",Name:"4月份"},
		    {Code:"5",Name:"5月份"},
		    {Code:"6",Name:"6月份"},
		    {Code:"7",Name:"7月份"},
		    {Code:"8",Name:"8月份"},
		    {Code:"9",Name:"9月份"},
		    {Code:"10",Name:"10月份"},
		    {Code:"11",Name:"11月份"},
		    {Code:"12",Name:"12月份"}
		];
		$('#span_month').combo({
			data:data,
			value: 'Code',
			text: 'Name',
			width :158,
			height:80,
			listId:'',
			defaultSelected: 0,
			editable: false,
			callback:{
				onChange: function(data){
					$("#mp_month").val(data.Code);
					THISPAGE.buildGridData();
					Utils.check($("#mp_shop_code").val(), $("#shop_name").val());
				}
			}
		}).getCombo();
	},
	buildGridData:function(){
		var mp_year = $("#mp_year").val();
		var mp_month = $("#mp_month").val();
		if(mp_year == "" || mp_month == ""){
			return;
		}
		var days = Utils.getDaysInOneMonth($("#mp_year").val(), $("#mp_month").val())
		var gridData = [];
		for (var i = 1; i <= days; i++) {
			gridData.push({day:i});
		}
		$('#grid').clearGridData();
		$("#grid").jqGrid('setGridParam', {datatype : 'local',data : gridData}).trigger("reloadGrid");
	},
    gridTotal:function(){
		var grid=$('#grid');
		var premoney=grid.getCol('premoney',false,'sum');
		var planmoney=grid.getCol('planmoney',false,'sum');
    	grid.footerData('set',{premoney:premoney,planmoney:planmoney});
    },
    initGrid:function(){
		var self=this;
		var colModel = [
	    	{label:'日期',name: 'day', index: 'day', width: 80, title: false,fixed:true,align:'center'},
	    	{label:'同期销售',name: 'premoney', index: 'premoney', width: 100, title: false,align:'right',formatter: PriceLimit.formatMoney},
	    	{label:'计划金额',name: 'planmoney', index: 'planmoney', width: 100, title: false,editable:true,align:'right'},
	    	{label:'备注',name: 'remark', index: 'remark', width: 200, title: false,editable:true},
	    	{label:'',name: 'ismodify', index: 'ismodify', width: 100, title: false,hidden:true}
	    ];
		$('#grid').jqGrid({
			datatype: 'local',
			width: $(parent).width()-32,
			height: $(parent).height()-242,
			altRows:true,
			gridview: true,
			onselectrow: false,
			colModel: colModel,
			sortable:false,
			rownumbers: true,//行号
			pager: '#page',//分页
			multiselect:false,//多选
			viewrecords: true,
			cmTemplate: {sortable:true,title:false},
			page: 1, //只有一页
			pgbuttons:false,
			pgtext:false,
			rowNum:99,//每页条数
			shrinkToFit:false,//表格是否自动填充
			footerrow: true,
			cellEdit: true,
            cellsubmit: 'clientArray',
			jsonReader: {
				root: 'data', 
				repeatitems : false,
				id: 'day'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.gridTotal();
			},
			formatCell:function (rowid, cellname, value, iRow, iCol){
            	self.selectRow.value=value;
				return value;
			},
			beforeSaveCell :function(rowid, cellname, value, iRow, iCol){
				if(self.selectRow.value == value){
					return value;
				}
				var mp_sell_money = $("#mp_sell_money").val();
				if(mp_sell_money == ""){
					return '';
				}
				if(cellname == 'planmoney'){
					if(value == '' || isNaN(value) || parseFloat(value)<0){
						Public.tips({type: 2, content : '请输入正数！'});
						return self.selectRow.value;
					}
					if(parseFloat(self.selectRow.value) == parseFloat(value)){
						return self.selectRow.value;
					}
					if(parseFloat(value).toFixed(2).length > 11 || Math.abs(parseFloat(value)) > 1e+11){
						return self.selectRow.value;
					}
					if(!THISPAGE.checkInutPlanSellMoney(rowid, value)){
						Public.tips({type: 2, content : '计划金额总和超出范围！'});
						return self.selectRow.value;
					}
					$("#grid").jqGrid('setRowData',rowid,{ismodify:'1'});
					return parseInt(value);
				}
				return value;
			},
			afterSaveCell:function(rowid, cellname, value, iRow, iCol){
				if (cellname == 'planmoney' && self.selectRow.value != value){
					THISPAGE.reallotPlanSellMoney();//重新分配金额
				}
			}
	    });
	},
	checkInutPlanSellMoney:function(rowid,value){
		var mp_sell_money = $("#mp_sell_money").val();
		var ids = $("#grid").jqGrid('getDataIDs');
		var totalModifyMoney = 0;
		for(var i=0;i < ids.length;i++){
			var rowData = $("#monthdatagrid").jqGrid("getRowData", ids[i]);
			if(rowData.ismodify == '1' && ids[i] != rowid){
				totalModifyMoney += parseFloat(rowData.planmoney);
			}
		}
		if(totalModifyMoney+parseFloat(value)>mp_sell_money){
			return false;
		}
		return true;
	},
	reallotPlanSellMoney:function(){//重新分配未修改计划金额
		
		var mp_sell_money = $("#mp_sell_money").val();
		
		var pl_sell_money = null;
		var ids = $("#grid").jqGrid('getDataIDs');
		var totalModifyMoney = 0;
		var modifyCount = 0;
		for(var i=0;i < ids.length;i++){
			var rowData = $("#grid").jqGrid("getRowData", ids[i]);
			if(rowData.ismodify == '1'){
				totalModifyMoney += parseFloat(rowData.planmoney);
				modifyCount++;
			}
		}
		//将未修改的月份首先平均分配
		var leftPlanMoney = mp_sell_money-totalModifyMoney;
		var money = 0;
		for(var i=0;i < ids.length;i++){
			var rowData = $("#grid").jqGrid("getRowData", ids[i]);
			if(rowData.ismodify == '0'){
				money = Math.round(leftPlanMoney/(ids.length-modifyCount));
				$("#grid").jqGrid('setRowData',ids[i],{planmoney:money});
			}
		}
		
		//同期数据参考需要将存在同期数据且未修改的月份重新按照比例分配
		var byPre = THISPAGE.$_byPreMatch.chkVal().join() ? true : false;
		if(byPre){
			var totalPreMoney = 0;
			var totalAllotMoney = 0;
			for(var i=0;i < ids.length;i++){
				var rowData = $("#grid").jqGrid("getRowData", ids[i]);
				if(rowData.ismodify == '0' && parseFloat(rowData.premoney) > 0){
					totalPreMoney += parseFloat(rowData.premoney);
					totalAllotMoney += parseFloat(rowData.planmoney);
				}
			}
			for(var i=0;i < ids.length;i++){
				var rowData = $("#grid").jqGrid("getRowData", ids[i]);
				if(rowData.ismodify == '0' && parseFloat(rowData.premoney) > 0){
					money = Math.round(totalAllotMoney*parseFloat(rowData.premoney)/totalPreMoney);
					$("#grid").jqGrid('setRowData',ids[i],{planmoney:money});
				}
			}
		}
		THISPAGE.gridTotal();
	},
	initEvent:function(){
		$("#btn_close").click(function(e){
			e.preventDefault();
			$.dialog.confirm('确定要放弃制定的月计划吗？',function(){
				api.close();
			});
		});
	}
};

THISPAGE.init();